//
//  LoginViewController.m
//  Findif
//
//  Created by Cicel Chen on 2018/10/18.
//  Copyright © 2018年 Cicel Chen. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"
#import "MainTabBarController.h"
#import <CommonCrypto/CommonDigest.h>
#import "WXApi.h"
#import <CoreLocation/CoreLocation.h>

@interface LoginViewController ()<UITextFieldDelegate,CLLocationManagerDelegate>

@property (nonatomic, weak)UIImageView * topImageView;
@property (nonatomic, strong)UILabel * phoneLabel;
@property (nonatomic, strong)UILabel * verifyLabel;
@property (nonatomic, strong)UILabel * loginLabel;
@property (nonatomic, strong)UITextField * phoneTextFiled;
@property (nonatomic, strong)UITextField * verifyTextFiled;
@property (nonatomic, strong)UIButton * nextButton;
@property (nonatomic, strong)UIButton * verifyButton;
@property (nonatomic, weak)UIButton * weixinButton;
@property (nonatomic, weak)UIImageView * weixinImageView;
@property (nonatomic, strong)UIView * oneLineView;
@property (nonatomic, strong)UIView * twoLineView;

@property (nonatomic, strong)NSTimer * countDownTimer;

@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation LoginViewController

//倒计时总的秒数
static NSInteger  secondsCountDown = 60;


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = ZRWhiteColor;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startLocation) name:@"updateUserLocal" object:nil];
    
    [self setupUI];
    [self loadState];
    [self startLocation];
}

- (void)setupUI {
    
    UIImageView * backImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    
    backImageView.userInteractionEnabled = YES;
    //    backImageView.contentMode = UIViewContentModeScaleAspectFill;
    backImageView.image = [UIImage imageNamed:@"组4"];
    
    [self.view addSubview:backImageView];
    
    UIImageView * topImageView = [UIImageView new];
    
    topImageView.image = [UIImage imageNamed:@"组1"];
    
    self.topImageView = topImageView;
    
    [backImageView addSubview:self.topImageView];
    
    
    self.phoneLabel = [self setupLabelWithTitle:@"手机号"];
    [backImageView addSubview:self.phoneLabel];
    self.verifyLabel = [self setupLabelWithTitle:@"验证码"];
    [backImageView addSubview:self.verifyLabel];
    self.loginLabel = [self setupLabelWithTitle:@"其他登录"];
    [backImageView addSubview:self.loginLabel];
    
    
    self.phoneTextFiled = [self setupTextFiledWithTitle:@"请输入手机号"];
    //    self.phoneTextFiled.delegate = self;
    [backImageView addSubview:self.phoneTextFiled];
    self.verifyTextFiled = [self setupTextFiledWithTitle:@"请输入验证码"];
    [backImageView addSubview:self.verifyTextFiled];
    
    self.oneLineView = [self setupLineView];
    [backImageView addSubview:self.oneLineView];
    self.twoLineView = [self setupLineView];
    [backImageView addSubview:self.twoLineView];
    
    self.verifyButton = [self setupButtonWithTitle:@"验证码" WithType:@"verify"];
    [backImageView addSubview:self.verifyButton];
    self.nextButton = [self setupButtonWithTitle:@"登录" WithType:@"next"];
    [backImageView addSubview:self.nextButton];
    
    UIButton * weixinButton = [UIButton new];
    
    [weixinButton setTitleColor:ColorWithRGB(0xF5E25B) forState:UIControlStateNormal];
    [weixinButton setTitle:@"微信登录" forState:UIControlStateNormal];
    [weixinButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    weixinButton.layer.cornerRadius = 5;
    weixinButton.layer.borderColor = [ColorWithRGB(0xF5E25B) CGColor];
    weixinButton.layer.borderWidth = 1;
    weixinButton.layer.masksToBounds = YES;
    weixinButton.hidden = YES;
    
    self.weixinButton = weixinButton;
    
    [self.view addSubview:self.weixinButton];
    
    
    UIImageView * weixinImageView = [UIImageView new];
    
    weixinImageView.image = [UIImage imageNamed:@"微信"];
    weixinImageView.hidden = YES;
    
    self.weixinImageView = weixinImageView;
    
    [self.weixinButton addSubview:self.weixinImageView];
}

- (void)loadState{
    
    if ([WXApi isWXAppInstalled]) {
        
        self.weixinButton.hidden = NO;
        self.weixinImageView.hidden = NO;
    }else {
        
        self.weixinButton.hidden = YES;
        self.weixinImageView.hidden = YES;
    }
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]])
    {
        //        NSLog(@"OK weixin://");
        self.weixinButton.hidden = NO;
        self.weixinImageView.hidden = NO;
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"wechat://"]])
    {
        //        NSLog(@"OK wechat://");
        self.weixinButton.hidden = NO;
        self.weixinImageView.hidden = NO;
    }
    //    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fb290293790992170://"]])
    //    {
    //        NSLog(@"OK fb——————://");
    //    }
}


- (void)viewDidLayoutSubviews{
    
    [self.topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(kStatusBarHeight + kNavHeight + 20 * SCREENH6);
        make.width.mas_equalTo(115 * SCREENH6);
        make.height.mas_equalTo(83 * SCREENH6);
    }];
    
    [self.phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topImageView.mas_bottom).offset(60 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(65 * SCREENH6);
    }];
    
    [self.phoneTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.phoneLabel);
        make.top.mas_equalTo(self.phoneLabel.mas_bottom).offset(10 * SCREENH6);
        make.height.mas_equalTo(40 * SCREENH6);
        make.width.mas_equalTo(180 * SCREENH6);
    }];
    
    [self.oneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.phoneTextFiled);
        make.trailing.mas_equalTo(self.view).offset(-60 * SCREENH6);
        make.height.mas_equalTo(1 * SCREENH6);
        make.top.mas_equalTo(self.phoneTextFiled.mas_bottom);
    }];
    
    [self.verifyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.oneLineView);
        make.width.mas_equalTo(60 * SCREENH6);
        make.centerY.mas_equalTo(self.phoneTextFiled);
        make.height.mas_equalTo(30 * SCREENH6);
    }];
    
    [self.verifyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.phoneLabel);
        make.top.mas_equalTo(self.oneLineView.mas_bottom).offset(30 * SCREENH6);
    }];
    
    [self.verifyTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.phoneTextFiled);
        make.top.mas_equalTo(self.verifyLabel.mas_bottom).offset(10 * SCREENH6);
    }];
    
    [self.twoLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.oneLineView);
        make.top.mas_equalTo(self.verifyTextFiled.mas_bottom);
    }];
    
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.twoLineView);
        make.top.mas_equalTo(self.twoLineView.mas_bottom).offset(45 * SCREENH6);
        make.height.mas_equalTo(35 * SCREENH6);
    }];
    
    [self.weixinButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.nextButton);
        make.top.mas_equalTo(self.nextButton.mas_bottom).offset(20 * SCREENH6);
    }];
    
    [self.weixinImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.weixinButton);
        make.leading.mas_equalTo(self.weixinButton).offset(65 * SCREENH6);
        make.width.mas_equalTo(20 * SCREENH6);
        make.height.mas_equalTo(16 * SCREENH6);
    }];
}

- (UIButton *)setupButtonWithImageName:(NSString *)image{
    
    UIButton * button = [UIButton new];
    
    [button setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside
     ];
    
    return button;
}

- (UIButton *)setupButtonWithTitle:(NSString *)string WithType:(NSString *)type{
    
    UIButton * button = [UIButton new];
    
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside
     ];
    [button setTitle:string forState:UIControlStateNormal];
    [button setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    
    
    if ([type isEqualToString:@"verify"]) {
        
        button.layer.cornerRadius = 10;
        [button setBackgroundColor:ColorWithRGB(0xFFDD48)];
        button.titleLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    }else{
        
        button.layer.cornerRadius = 5;
        [button setBackgroundColor:ColorWithRGB(0xF5E25B)];
        button.titleLabel.font = [UIFont systemFontOfSize:18 * SCREENH6];
    }
    button.layer.masksToBounds = YES;
    
    return button;
}

- (UIView *)setupLineView{
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ZRWhiteColor;
    
    return lineView;
}

- (UITextField *)setupTextFiledWithTitle:(NSString *)title{
    
    UITextField * textFiled = [[UITextField alloc] init];
    
    textFiled.borderStyle = UITextBorderStyleNone;
    textFiled.backgroundColor = [UIColor clearColor];
    textFiled.layer.borderColor = [[UIColor clearColor] CGColor];
    //设置光标颜色
    textFiled.tintColor = ZRWhiteColor;
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0xa5a5a5);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:title attributes:attrs];
    textFiled.textColor = ZRWhiteColor;
    //    textFiled.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //    //设置显示模式为永远显示(默认不显示)
    //    textFiled.leftViewMode = UITextFieldViewModeAlways;
    textFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    textFiled.keyboardAppearance = UIKeyboardAppearanceDark;
    textFiled.keyboardType = UIKeyboardTypePhonePad;
    textFiled.delegate = self;
    
    return textFiled;
}

- (UILabel *)setupLabelWithTitle:(NSString *)title{
    
    UILabel * label = [UILabel new];
    
    label.textColor = ZRWhiteColor;
    label.font = [UIFont systemFontOfSize:18 * SCREENH6];
    label.text = title;
    
    return label;
}


- (void)clickButton:(UIButton *)button{
    
    //=============================点击获取验证码，验证手机号。=================
    if (button == self.verifyButton) {
        
        BOOL next = [self isMobileNumber:self.phoneTextFiled.text];
        
        if (next) {
            [self.verifyButton resignFirstResponder];
            secondsCountDown = 59;
            
            //设置定时器
            _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
            
            [self.verifyButton setTitle:[NSString stringWithFormat:@"%ld",secondsCountDown] forState:UIControlStateNormal];
            
            [[ZRNetworkTool sharedTool] sendMsgWithPhone:self.phoneTextFiled.text resultWithBlock:^(BOOL success, id responseData) {
                
                if (success) {
                    
                }
            }];
            
        }else{
            
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"请输入正确的手机号"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        //=============================点击下一步按钮=================
    }else if (button == self.nextButton){
        
        NSString * lon = DEF_GET_OBJECT(@"lon");
        NSString * lat = DEF_GET_OBJECT(@"lat");
        
        if (lon && lat) {
        
            [self pushToNextViewControllerWithLat:lat WithLon:lon];
            
        }else{

//            HiddenHUD;
//
//            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
//                                                                           message:@"为了给您更好的服务，请打开定位服务"
//                                                                    preferredStyle:UIAlertControllerStyleAlert];
//
//            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
//                                                                  handler:^(UIAlertAction * action) {
//
//                                                                  }];
//
//            [alert addAction:defaultAction];
//            [self presentViewController:alert animated:YES completion:nil];
            
            [self pushToNextViewControllerWithLat:@"" WithLon:@""];
        }
        
    }else if (button == self.weixinButton){
        
        if ([WXApi isWXAppInstalled]) {
            
            SendAuthReq *req = [[SendAuthReq alloc] init];
            req.scope = @"snsapi_userinfo";
            req.state = @"App";
            [WXApi sendReq:req];
        }
        else {
            
            [self setupAlertController];
        }
        
    }
    
    
}


- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    if (self.phoneTextFiled.text.length > 0 && self.verifyTextFiled.text.length > 0) {
        
        NSString * lon = DEF_GET_OBJECT(@"lon");
        NSString * lat = DEF_GET_OBJECT(@"lat");
        
        if (lon && lat) {
        
            [self pushToNextViewControllerWithLat:lat WithLon:lon];
        }else{

            [self pushToNextViewControllerWithLat:@"" WithLon:@""];
        }
        
    }
}


- (void)pushToNextViewControllerWithLat:(NSString *)lat WithLon:(NSString *)lon{
    
    if (self.phoneTextFiled.text.length > 0 && self.verifyTextFiled.text.length > 0) {
        
        ShowHUD;
        
        [[ZRNetworkTool sharedTool] veriftCodeWithPhone:self.phoneTextFiled.text WithCode:self.verifyTextFiled.text resultWithBlock:^(BOOL success, id responseData) {
            
            if (success) {
                
                [[ZRNetworkTool sharedTool] loginWithPhone:self.phoneTextFiled.text WithLat:lat WithLon:lon resultWithBlock:^(BOOL success, id responseData) {
                    
                    HiddenHUD;
                    
                    if (success) {
                        
                        NSDictionary * dict = responseData[@"data"];
                        NSString * ID = dict[@"id"];
                        DEF_SET_OBJECT(ID, @"id");
                        DEF_SET_OBJECT(self.phoneTextFiled.text, @"phone");
                        
                        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                        
                        MainTabBarController *tabs = [[MainTabBarController alloc] init];
                        
                        appDelegate.window.rootViewController = tabs;
                    }else{
                        
                        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                       message:responseData[@"message"]
                                                                                preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                              handler:^(UIAlertAction * action) {
                                                                                  
                                                                              }];
                        
                        [alert addAction:defaultAction];
                        [self presentViewController:alert animated:YES completion:nil];
                    }
                }];
            }else{
                
                HiddenHUD;
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }else{
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"请完善登录信息后登录~"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}


//定时器的方法
- (void)countDownAction{
    
    secondsCountDown --;
    
    [self.verifyButton setTitle:[NSString stringWithFormat:@"%ld",secondsCountDown] forState:UIControlStateNormal];
    self.verifyButton.enabled = NO;
    //当倒计时到0时做需要的操作，button变成可选状态
    if(secondsCountDown==0){
        
        [_countDownTimer invalidate];
        
        [self.verifyButton setTitle:@"验证码" forState:UIControlStateNormal];
        
        self.verifyButton.enabled = YES;
    }
}


- (BOOL)isMobileNumber:(NSString *)mobileNum {
    
    //    电信号段:133/149/153/180/181/189/173/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170/171
    
    NSString *MOBILE = @"^1(3[0-9]|4[579]|5[0-35-9]|8[0-9]|7[0136-8])\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:mobileNum];
}

#pragma mark - 设置弹出提示语
- (void)setupAlertController {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:actionConfirm];
    [self presentViewController:alert animated:YES completion:nil];
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.phoneTextFiled resignFirstResponder];
    [self.verifyTextFiled resignFirstResponder];
}

- (void)viewDidDisappear:(BOOL)animated{
    
    [_countDownTimer invalidate];
}


//开始定位
- (void)startLocation {
    
    if ([CLLocationManager locationServicesEnabled]) {
        //        CLog(@"--------开始定位");
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        //控制定位精度,越高耗电量越
        self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        // 总是授权
        [self.locationManager requestWhenInUseAuthorization];
        self.locationManager.distanceFilter = 10.0f;
        //        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}
//定位代理经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    CLLocation *newLocation = locations[0];
    
    //    self.userLocation = newLocation;
    
    double lat = newLocation.coordinate.latitude;
    double lon = newLocation.coordinate.longitude;
    
    NSString * latStr = [NSString stringWithFormat:@"%f",lat];
    NSString * lonStr = [NSString stringWithFormat:@"%f",lon];
    
    DEF_SET_OBJECT(latStr, @"lat");
    DEF_SET_OBJECT(lonStr, @"lon");
}

@end
